//
//  YBFileShowVC.m
//  ChangChat
//
//  Created by Cocoa on 2019/9/5.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "YBFileShowVC.h"
#import "ZXConfirmButton.h"
#import "YBApiManager+Global.h"
#import "CacheHelper.h"
#import <LKDBHelper/LKDBHelper.h>
#import "TTOpenInAppActivity.h"

@interface YBFileShowVC ()<UIDocumentInteractionControllerDelegate>

@property (nonatomic, strong) UIView *msgContentView;
@property (nonatomic, strong) UIImageView *fileImgView;
@property (nonatomic, strong) UILabel *fileNameLabel;
@property (nonatomic, strong) UILabel *fileSizeLabel;


@property (nonatomic, strong) UIButton *otherOpenBtn;

@property (nonatomic, assign) BOOL loading;
@property (nonatomic, strong) UIView *progressView;

@property (nonatomic, strong) UIDocumentInteractionController *DIC;

@end

@implementation YBFileShowVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    self.title = @"文件";
    self.fileNameLabel.text = _msgModel.msg.file_name;
    self.fileSizeLabel.text = _msgModel.msg.file_size;
    
    if (_msgModel.msg.filePath.isHaveStr == NO ||
        [FileUtils isFileExists:_msgModel.msg.allFilePath] == NO) {
        [self downloadFile];
    }
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: UIColor.k_t2Color} forState:UIControlStateNormal ];
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: UIColor.k_t3Color} forState: UIControlStateHighlighted];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal ];
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState: UIControlStateHighlighted];
}
- (NSString *)getFilePathWithFileName:(NSString *)name {
    NSString *filePath = [[FileUtils documentsDirectory] stringByAppendingPathComponent:@"msg_file/"];
    NSString *allPath = [filePath stringByAppendingPathComponent:name];
    return allPath;
}
- (void)downloadFile {
    if (self.progressView == nil) {
        self.progressView = [[UIView alloc] initWithFrame:CGRectMake(0, NavigationBarHeight, 0, 3)];
        self.progressView.backgroundColor = UIColor.k_t1Color;
        [self.view addSubview:self.progressView];
    }
    self.loading = YES;
    @weakify(self);
    self.progressView.hidden = NO;
    self.progressView.width = 0;
    NSString *filePath = [[CacheHelper helper] allFilePathWithMsgType:self.msgModel.msg.type fileName:self.msgModel.msg.file_name];
    
    [UIView animateWithDuration:0.2 animations:^{
        self.progressView.width = 30;
    }];
    [[YBApiManager.shareManager downloadTask:self.msgModel.msg.content filePath:filePath] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        if ([x isKindOfClass:NSNumber.class] == YES) {
            double pro = [x doubleValue];
            [UIView animateKeyframesWithDuration:0.2 delay:0 options:UIViewKeyframeAnimationOptionBeginFromCurrentState animations:^{
                self.progressView.width = ScreenWidth * pro;
            } completion:nil];
            
        } else {
            [UIView animateKeyframesWithDuration:0.5 delay:0 options:UIViewKeyframeAnimationOptionBeginFromCurrentState animations:^{
                self.progressView.width = ScreenWidth;
            } completion:^(BOOL finished) {
                self.progressView.hidden = YES;
            }];
//            NSURL *fileURL = x;
            self.msgModel.msg.filePath = self.msgModel.msg.file_name;
            [self.msgModel.msg updateToDB];

        }
        self.loading = NO;
    } error:^(NSError * _Nullable error) {
        self.loading = NO;
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
    }];
}


- (void)setupUI {
    
    self.msgContentView = UIView.new;
    [self.view addSubview:self.msgContentView];
    self.otherOpenBtn = [ZXConfirmButton confirmButton];
    self.otherOpenBtn.k_title(@"用其他应用打开");
    [self.view addSubview:self.otherOpenBtn];
    [self.otherOpenBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.mas_offset(-50);
        make.left.mas_offset(50);
        make.height.mas_equalTo(40);
    }];
    [self.otherOpenBtn addTarget:self action:@selector(didClickOtherAPPOpenBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.msgContentView.backgroundColor = UIColor.whiteColor;
    self.fileImgView = [UIImageView new];
    self.fileImgView.image = UIImage.k_imgName(@"msg_placeholder_file");
    self.fileNameLabel = [UILabel k_labelWithFontSize:15 textColor:UIColor.k_t2Color];
    self.fileNameLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    self.fileNameLabel.numberOfLines = 2;
    self.fileSizeLabel = [UILabel k_labelWithFontSize:12 textColor:UIColor.k_t3Color];
    
    [self.msgContentView addSubview:self.fileImgView];
    [self.msgContentView addSubview:self.fileNameLabel];
    [self.msgContentView addSubview:self.fileSizeLabel];
    self.msgContentView.backgroundColor = UIColor.whiteColor;
    
    [self.fileImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_offset(15);
        make.size.mas_equalTo(CGSizeMake(40, 43));
        make.bottom.mas_offset(-15).priorityLow();
    }];
    [self.fileNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.fileImgView.mas_right).offset(5);
        make.right.mas_offset(-15);
        make.top.equalTo(self.fileImgView);
    }];
    
    [self.fileSizeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.fileNameLabel);
        make.top.equalTo(self.fileNameLabel.mas_bottom).offset(5);
        make.bottom.lessThanOrEqualTo(self.msgContentView).offset(-15);
    }];
    
    [self.msgContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(50);
        make.right.mas_offset(-50);
        make.center.equalTo(self.view);
    }];
}

- (void)didClickOtherAPPOpenBtnAction:(UIButton *)sender {
    if (self.msgModel.msg.filePath.isHaveStr == NO ) {
        if (self.loading == NO) {
            [MBProgressHUD showTipMessageInView:@"您的文件还未下载，正在重新下载文件。" timer:1.5f];
            [self downloadFile];
        } else {
            [MBProgressHUD showTipMessageInView:@"您的文件正在下载中， 请下载完成后打开。" timer:1.5f];
        }
        return;
    }
    
    
    NSString *newPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"msg_file/"];
    NSString *filePath = [newPath stringByAppendingPathComponent:self.msgModel.msg.filePath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:newPath] == NO) {
        [fileManager createDirectoryAtPath:newPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    [FileUtils moveFile:self.msgModel.msg.allFilePath desPath:filePath];
    
//    UIDocumentInteractionController *documentController = [UIDocumentInteractionController interactionControllerWithURL:newPath.fileToURL];
//    documentController.delegate = self;
//    self.DIC = documentController;
////    documentController.UTI = @"com.microsoft.word.doc.docx.mp3";
//    BOOL canPresent = [documentController presentPreviewAnimated:YES];
//    if (canPresent == NO) {
//        canPresent = [documentController presentOpenInMenuFromRect:CGRectMake(760, 20, 100, 100) inView:self.view animated:YES];
//        if (canPresent == NO) {
//            [MBProgressHUD showTipMessageInView:@"文件不支持打开" timer:1.5f];
//        }
//    }

    
    NSURL *URL = [NSURL fileURLWithPath:filePath];
    
    TTOpenInAppActivity *openInAppActivity;
    
    if ([sender isKindOfClass:[UIButton class]]){
        openInAppActivity = [[TTOpenInAppActivity alloc] initWithView:self.view andRect:((UIButton *)sender).frame];
    } else {
        openInAppActivity = [[TTOpenInAppActivity alloc] initWithView:self.view andBarButtonItem:(UIBarButtonItem *)sender];
    }
    
    UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[URL] applicationActivities:@[openInAppActivity]];
    activityViewController.popoverPresentationController.sourceView = self.view;
    if ([sender isKindOfClass:[UIButton class]]){
        activityViewController.popoverPresentationController.sourceRect = ((UIButton *)sender).frame;
    } else {
        activityViewController.popoverPresentationController.barButtonItem = (UIBarButtonItem *)sender;
    }
    
    // Show UIActivityViewController
    [self presentViewController:activityViewController animated:YES completion:NULL];
    
}

-(UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    
    return self;
}
-(UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller {
    return self.view;
}
- (void)documentInteractionControllerWillBeginPreview:(UIDocumentInteractionController *)controller {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"%@, %@", [UIWindow fj_topVC], [UIWindow fj_topVC].navigationController);
    });
}
- (void)documentInteractionController:(UIDocumentInteractionController *)controller willBeginSendingToApplication:(NSString *)application {
    NSLog(@"\n%s [Line %d], application = %@", __PRETTY_FUNCTION__, __LINE__, application);
}
- (void)documentInteractionController:(UIDocumentInteractionController *)controller didEndSendingToApplication:(NSString *)application {
    NSLog(@"\n%s [Line %d], application = %@", __PRETTY_FUNCTION__, __LINE__, application);
}


@end
